package com.tma.demo;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class SlideShowHandler extends Handler {
    private int mIndex = 0;
    private int mImgIds[] = { R.drawable.scenery1, R.drawable.scenery2,
            R.drawable.scenery3, R.drawable.scenery4 };

    private ImageView mImageView;
    private Animation mAnimation;
    private long mInterval = 2; // second
    private boolean mIsPlay = false;

    public SlideShowHandler(Context context, ImageView imageview) {
        mImageView = imageview;
        mAnimation = AnimationUtils.loadAnimation(context, R.anim.l2r);
    }

    @Override
    public void handleMessage(Message msg) {
        if (!mIsPlay) {
            return;
        }

        if (mIndex >= mImgIds.length) {
            mIndex = 0;
        }

        mImageView.startAnimation(mAnimation);
        mImageView.setImageResource(mImgIds[mIndex]);
        mIndex++;

        next();
    }

    private void next() {
        Message msg = Message.obtain();
        sendMessageDelayed(msg, mInterval * 1000);
    }

    public void play() {
        if (!mIsPlay) {
            mIndex = 0;
            mIsPlay = true;
            next();
        }
    }

    public void stop() {
        mIsPlay = false;
    }
}
